class Cpanel::QiniuController < Cpanel::BaseController
  skip_before_action :pundit_authorized

  # 获取上传的token
  def uptoken
    key = AnAnCommon::Qiniu.generate_uploader_key(Time.current.to_i.to_s, 'jpg')

    # 构建上传策略，上传策略的更多参数请参照 http://developer.qiniu.com/article/developer/security/put-policy.html
    put_policy             = Qiniu::Auth::PutPolicy.new(::AnAnCommon::QINIU_BUCKET, nil, 3600)
    put_policy.fsize_limit = 5.megabytes
    put_policy.save_key    = key
    put_policy.return_body = ActiveSupport::JSON.encode(bucket: '$(bucket)', key: '$(key)')

    # 生成上传 Token
    uptoken = Qiniu::Auth.generate_uptoken(put_policy)
    render json: { uptoken: uptoken }
  end

  def simditor_uploader
    key = AnAnCommon::Qiniu.generate_uploader_key('simditor', 'jpg')
    resp_code, = AnAnCommon::Qiniu.upload_file(params[:upload_file].path, key)
    if resp_code == 200
      render json: { success: true, msg: '上传成功！', file_path: AnAnCommon::Qiniu.url(key) }
    else
      render json: { success: false }
    end
  end
end
